"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { InfoIcon, Upload } from "lucide-react";
import { SwpTable } from "@/lib/swp/table/swp-table";
import { SwpInboxTable } from "@/lib/swp/table/swp-inbox-table";
import { SwpTableToolbar } from "@/lib/swp/table/swp-table-toolbar";
import {
  fetchVendorDocuments,
  fetchVendorProjects,
  fetchVendorSwpStats,
  getVendorSessionInfo,
  fetchVendorUploadedFiles,
} from "@/lib/swp/vendor-actions";
import type { DocumentListItem } from "@/lib/swp/document-service";
import type { SwpFileApiResponse } from "@/lib/swp/api-client";
import { toast } from "sonner";

interface VendorDocumentPageProps {
  searchParams: { [key: string]: string | string[] | undefined };
}

export default function VendorDocumentPage({ searchParams }: VendorDocumentPageProps) {
  // URL에서 프로젝트 번호만 사용 (나머지는 클라이언트 필터링)
  const initialProjNo = (searchParams.projNo as string) || "";

  // 상태 관리
  const [documents, setDocuments] = useState<DocumentListItem[]>([]);
  const [inboxFiles, setInboxFiles] = useState<SwpFileApiResponse[]>([]);
  const [requiredDocs, setRequiredDocs] = useState<Array<{ vendorDocNumber: string; title: string; buyerSystemComment: string | null }>>([]);
  const [projNo, setProjNo] = useState(initialProjNo);
  const [projects, setProjects] = useState<Array<{ PROJ_NO: string; PROJ_NM: string }>>([]);
  const [stats, setStats] = useState({
    total_documents: 0,
    total_revisions: 0,
    total_files: 0,
    uploaded_files: 0,
    last_sync: null as Date | null,
  });
  const [vendorInfo, setVendorInfo] = useState<{
    vendorId: number;
    vendorCode: string;
    vendorName: string;
    companyId: number;
  } | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 탭 상태
  const [activeTab, setActiveTab] = useState("inbox");

  // 클라이언트 필터
  const [searchFilters, setSearchFilters] = useState({
    docNo: (searchParams.docNo as string) || "",
    docTitle: (searchParams.docTitle as string) || "",
    pkgNo: (searchParams.pkgNo as string) || "",
    stage: (searchParams.stage as string) || "",
    status: (searchParams.status as string) || "",
  });

  // Dropzone 설정
  const [droppedFiles, setDroppedFiles] = useState<File[]>([]);

  // 파일 드롭 핸들러
  const onDrop = useCallback((acceptedFiles: File[]) => {
    if (acceptedFiles.length > 0) {
      setDroppedFiles(acceptedFiles);
    }
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    noClick: true, // 클릭으로 파일 선택 비활성화 (버튼을 통해서만 선택)
    noKeyboard: true,
  });

  const loadInitialData = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      // 병렬로 데이터 로드
      const [vendorInfoData, projectsData] = await Promise.all([
        getVendorSessionInfo(),
        fetchVendorProjects(),
      ]);

      setVendorInfo(vendorInfoData);
      setProjects(projectsData);

      // 초기 프로젝트가 있으면 문서 로드
      if (initialProjNo) {
        const [documentsData, statsData, uploadedData] = await Promise.all([
          fetchVendorDocuments(initialProjNo),
          fetchVendorSwpStats(initialProjNo),
          fetchVendorUploadedFiles(initialProjNo),
        ]);
        setDocuments(documentsData);
        setStats(statsData);
        setInboxFiles(uploadedData.files);
        setRequiredDocs(uploadedData.requiredDocs);
      }
    } catch (err) {
      console.error("Failed to load initial data:", err);
      setError(err instanceof Error ? err.message : "Failed to load data");
      toast.error("Failed to load data");
    } finally {
      setIsLoading(false);
    }
  }, [initialProjNo]);

  const loadDocuments = useCallback(async () => {
    if (!projNo) return;

    try {
      setIsRefreshing(true);
      setError(null);

      const [documentsData, statsData, uploadedData] = await Promise.all([
        fetchVendorDocuments(projNo),
        fetchVendorSwpStats(projNo),
        fetchVendorUploadedFiles(projNo),
      ]);

      setDocuments(documentsData);
      setStats(statsData);
      setInboxFiles(uploadedData.files);
      setRequiredDocs(uploadedData.requiredDocs);
      toast.success("Document list refreshed");
    } catch (err) {
      console.error("Failed to load documents:", err);
      setError(err instanceof Error ? err.message : "Failed to load documents");
      toast.error("Failed to load documents");
    } finally {
      setIsRefreshing(false);
    }
  }, [projNo]);

  // 초기 데이터 로드
  useEffect(() => {
    loadInitialData();
  }, [loadInitialData]);

  // 프로젝트 변경 시 문서 재로드
  useEffect(() => {
    if (!isLoading && projNo) {
      loadDocuments();
    }
  }, [projNo, isLoading, loadDocuments]);

  const handleProjectChange = (newProjNo: string) => {
    setProjNo(newProjNo);
  };

  const handleFiltersChange = (filters: typeof searchFilters) => {
    setSearchFilters(filters);
  };

  const handleRefresh = () => {
    loadDocuments();
  };

  const handleUploadComplete = () => {
    // 업로드 완료 시 Inbox 탭으로 전환
    setActiveTab("inbox");
  };

  // 클라이언트 사이드 필터링 - VDR Documents
  const filteredDocuments = useMemo(() => {
    return documents.filter((doc) => {
      if (searchFilters.docNo && !doc.DOC_NO.toLowerCase().includes(searchFilters.docNo.toLowerCase())) {
        return false;
      }
      if (searchFilters.docTitle && !doc.DOC_TITLE.toLowerCase().includes(searchFilters.docTitle.toLowerCase())) {
        return false;
      }
      if (searchFilters.pkgNo && !doc.PKG_NO?.toLowerCase().includes(searchFilters.pkgNo.toLowerCase())) {
        return false;
      }
      if (searchFilters.stage && doc.STAGE !== searchFilters.stage) {
        return false;
      }
      if (searchFilters.status) {
        const statusLower = searchFilters.status.toLowerCase();
        const docStatus = doc.LTST_ACTV_STAT?.toLowerCase() || "waiting";
        if (!docStatus.includes(statusLower)) {
          return false;
        }
      }
      return true;
    });
  }, [documents, searchFilters]);

  // 클라이언트 사이드 필터링 - Inbox Files
  const filteredInboxFiles = useMemo(() => {
    return inboxFiles.filter((file) => {
      if (searchFilters.docNo && !file.OWN_DOC_NO.toLowerCase().includes(searchFilters.docNo.toLowerCase())) {
        return false;
      }
      if (searchFilters.docTitle && !file.FILE_NM.toLowerCase().includes(searchFilters.docTitle.toLowerCase())) {
        return false;
      }
      if (searchFilters.pkgNo && !file.PKG_NO?.toLowerCase().includes(searchFilters.pkgNo.toLowerCase())) {
        return false;
      }
      if (searchFilters.stage && file.STAGE !== searchFilters.stage) {
        return false;
      }
      if (searchFilters.status) {
        const statusLower = searchFilters.status.toLowerCase();
        const fileStatus = file.STAT_NM?.toLowerCase() || file.STAT?.toLowerCase() || "";
        if (!fileStatus.includes(statusLower)) {
          return false;
        }
      }
      return true;
    });
  }, [inboxFiles, searchFilters]);

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-4 w-96" />
        </CardHeader>
        <CardContent className="space-y-4">
          <Skeleton className="h-32 w-full" />
          <Skeleton className="h-96 w-full" />
        </CardContent>
      </Card>
    );
  }

  return (
    <div {...getRootProps()} className="relative w-full min-w-0">
      <input {...getInputProps()} />
      
      {/* 드래그 오버레이 */}
      {isDragActive && (
        <div className="fixed inset-0 z-50 bg-primary/20 backdrop-blur-sm flex items-center justify-center">
          <div className="bg-background border-2 border-dashed border-primary rounded-lg p-12 text-center space-y-4">
            <Upload className="h-16 w-16 mx-auto text-primary animate-bounce" />
            <div className="space-y-2">
              <p className="text-2xl font-semibold">Drop files here</p>
              <p className="text-muted-foreground">
                You can upload multiple files at once
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="space-y-6">
        {/* 에러 메시지 */}
        {error && (
          <Alert variant="destructive">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {/* 통계 카드 */}
        {/* <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>할당된 문서</CardDescription>
              <CardTitle className="text-3xl">{stats.total_documents.toLocaleString()}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>총 리비전</CardDescription>
              <CardTitle className="text-3xl">{stats.total_revisions.toLocaleString()}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>총 파일</CardDescription>
              <CardTitle className="text-3xl">{stats.total_files.toLocaleString()}</CardTitle>
            </CardHeader>
          </Card>
          <Card>
            <CardHeader className="pb-3">
              <CardDescription>업로드한 파일</CardDescription>
              <CardTitle className="text-3xl text-green-600">
                {stats.uploaded_files.toLocaleString()}
              </CardTitle>
            </CardHeader>
          </Card>
        </div> */}

        {/* 안내 메시지 */}
        {documents.length === 0 && !projNo && (
          <Alert>
            <InfoIcon className="h-4 w-4" />
            <AlertDescription>
              Select a project to view assigned documents.
            </AlertDescription>
          </Alert>
        )}

        {/* 메인 테이블 - 탭 구조 */}
        <Card className="w-full overflow-hidden">
          <CardHeader>
            <SwpTableToolbar
              projNo={projNo}
              filters={searchFilters}
              onProjNoChange={handleProjectChange}
              onFiltersChange={handleFiltersChange}
              onRefresh={handleRefresh}
              onUploadComplete={handleUploadComplete}
              isRefreshing={isRefreshing}
              projects={projects}
              vendorCode={vendorInfo?.vendorCode}
              droppedFiles={droppedFiles}
              onFilesProcessed={() => setDroppedFiles([])}
              documents={filteredDocuments}
              userId={String(vendorInfo?.vendorId || "")}
              requiredDocs={requiredDocs}
            />
          </CardHeader>
          <CardContent>
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="inbox">
                  DOCUMENT REGISTRATION
                  {/* ({filteredInboxFiles.length}) */}
                </TabsTrigger>
                <TabsTrigger value="documents">
                  DOCUMENT LIST
                  {/* ({filteredDocuments.length}) */}
                </TabsTrigger>
              </TabsList>
              <TabsContent value="inbox" className="mt-4">
                <SwpInboxTable
                  files={filteredInboxFiles}
                  requiredDocs={requiredDocs}
                  projNo={projNo}
                  vendorCode={vendorInfo?.vendorCode || ""}
                  userId={String(vendorInfo?.vendorId || "")}
                />
              </TabsContent>
              <TabsContent value="documents" className="mt-4">
                <SwpTable
                  documents={filteredDocuments}
                  projNo={projNo}
                  vendorCode={vendorInfo?.vendorCode || ""}
                  userId={String(vendorInfo?.vendorId || "")}
                />
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
